package com.brillilab.service.logic.instrument.converter;

import com.brillilab.common.constant.ResultEnum;
import com.brillilab.common.exceptions.BrillilabException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间类型转换器
 *
 * @author wmh
 */
public class DateConverter {

    private static final Logger log = LoggerFactory.getLogger(DateConverter.class);

    private DateConverter() {
    }

    /**
     * 时间字符串转换为Date
     * @param source
     * @return
     */
    public static Date stringToDate(String source){
        SimpleDateFormat simpleDateFormat=null;
        //"yyyy/MM/dd HH:mm:ss"
        if (source.matches("^[1-2][0-9]{3}[/]([1][0-2]|[0][1-9])[/]([0-2][0-9]|3[0-1])\\s([0-1][0-9]|[2][0-3])[:]([0-5]?[0-9])[:]([0-5]?[0-9])$")){
            simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        }
        //"HH:mm:ss"
        else if (source.matches("^([0-1][0-9]|[2][0-3])[:]([0-5]?[0-9])[:]([0-5]?[0-9])$")){
            simpleDateFormat=new SimpleDateFormat("HH:mm:ss");
        }
        //格式不符合
        else{
            simpleDateFormat=new SimpleDateFormat();
            log.error("日期参数格式错误！");
            throw new BrillilabException(ResultEnum.TIME_FORMAT_ERROR);
        }
        try {
            Date result = simpleDateFormat.parse(source);
            return result;
        } catch (ParseException e) {
            log.warn("时间参数转化异常:"+source+"无法被转换！");
            return null;
        }
    }

    /**
     * Date转化为时间字符串
     * @param date
     * @return
     */
    public static String DateToString(Date date){

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        try {
            //比2018早 HH:mm:ss
            if (date.getTime()< simpleDateFormat.parse("2018/01/01 00:00:00").getTime()){
                return new SimpleDateFormat("HH:mm:ss").format(date);
            //比2018晚 yyyy/MM/dd HH:mm:ss
            }else{
                return simpleDateFormat.format(date);
            }
        } catch (ParseException e) {
            log.warn("时间参数转化异常:"+date+"无法被转换！");
            return null;
        }

    }
}
